package al.xc.redis;


import al.xc.common.util.SingleUtils;
import redis.clients.jedis.JedisPoolConfig;

public class RedisConnectManager {

    IRedisConnect connect_ = null;

    /**
     * 初始化线程
     */
    public void initialize(IRedisConfig config) {
        config.showConfig();

        JedisPoolConfig config1 = new JedisPoolConfig();
        config1.setMaxTotal(config.getRedisPoolConfigMaxTotal());
        config1.setMaxIdle(config.getRedisPoolConfigMaxIdle());
        config1.setMaxWaitMillis(config.getRedisPoolConfigMaxWaitMillis());
        config1.setTestOnBorrow(config.getRedisPoolConfigTestOnBorrow());
        config1.setTestOnReturn(config.getRedisPoolConfigTestOnReturn());

        config1.setTestWhileIdle(config.getRedisPoolConfigTestWhileIdle());
        config1.setTimeBetweenEvictionRunsMillis(config.getTimeBetweenEvictionRunsMillis());
        config1.setNumTestsPerEvictionRun(config.getNumTestsPerEvictionRun());
        config1.setMinEvictableIdleTimeMillis(config.getMinEvictableIdleTimeMillis());

        String[] urlList = config.getRedisUrls().split(",");

        String[] hosts = new String[urlList.length];
        int[] ports = new int[urlList.length];
        for (int i = 0; i < urlList.length; ++i) {
            hosts[i] = urlList[i].split(":")[0].trim();
            ports[i] = Integer.parseInt(urlList[i].split(":")[1].trim());
        }
        if (urlList.length == 1) {
            connect_ = SingleUtils.instance(IRedisConnect.class, new RedisConnectSingle());
        } else {
            connect_ = SingleUtils.instance(IRedisConnect.class, new RedisConnectCluster());
        }

        connect_.initialize(config1, hosts, ports, config.getRedisTimeout(), config.getRedisPassword(), config.getRedisDatabaseIndex());
    }

    /**
     * 反初始化
     */
    public void unInitialize() {
    }

    /**
     * redis连接池
     *
     * @return
     */
    public IRedisConnect connect() {
        return connect_;
    }
}